/** @format */

import * as qiniu from 'qiniu-js'
import { Toast } from 'vant'

const mimeTypes = {
    PNG: 'image/png',
    JPEG: 'image/jpeg',
    WEBP: 'image/webp',
    BMP: 'image/bmp'
}

const supportMimeTypes = Object.values(mimeTypes)

export const getQiNiuUpToken = async() => {
    const result = await fetch(
            'https://mobile.jingyunhrs.com/qiniu/upload-token'
        )
        .then(res => res.json())
        .then(res => res.data)
        .catch(() => {
            Toast('上传失败')
        })
    return result
}

/**
 * 上传文件至七牛
 * @param file {File} File
 * @param onUploadProgress {function} 上传中进度callback
 * @returns {Promise<PromiseLike<string> | Promise<string>> | undefined}
 */
export async function uploadToQiniu(file, onUploadProgress = () => {}) {
    const token = await getQiNiuUpToken()
    console.log(token, 'qiniutoken')
    if (!token) return

    return new Promise((resolve, reject) => {
        const uploadTask = source => {
            const config = { useCdnDomain: true }
            const observable = qiniu.upload(source, null, token, {}, config)
            observable.subscribe({
                next(res) {
                    onUploadProgress(res.total)
                },
                error(err) {
                    reject(err)
                    Toast('上传失败')
                    throw err
                },
                complete(res) {
                    console.log(res, 'completehash')
                    resolve(`https://qiniu.jingyunhrs.com/${res.key}`)
                }
            })
        }

        if (supportMimeTypes.includes(file.type)) {
            const options = { quality: 0.92, noCompressIfLarger: true }
            qiniu.compressImage(file, options).then(data => {
                uploadTask(data.dist)
            })
            return
        }

        uploadTask(file)
    })
}